﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using PIM_ATE.Mods;
using System.IO;

namespace PIM_ATE
{
    public partial class FrmMain : Form
    {
        public FrmMain(ClsDataUser user)
        {
            InitializeComponent();
            int size = 945;
            this.Size = new Size(size, size * 3 / 4);
            this.Text = "互调测试 1.5";
            m_isLocalConfg = GDefine.IS_LOCAL_CONFIG_ANTENNA;
            m_userObj = user;
        }

        SplitContainer ctl_pim_container1;
        SplitContainer ctl_pim_container2;
        CurveChart ctl_pim_ccPlot;
        DataGridView ctl_pim_dgvData;
        TextBox ctl_pim_tbLog;

        ClsDataConfigLocalBuilder m_pim_cfgDataBuilder_local;
        List<ClsDataConfigLocal> m_pim_lstCfgData_local;
        DataTable m_pim_dtShow;
        DataTable m_pim_dtShowDBC;
        List<bool> m_enableConfig;


        System.Threading.Timer m_time_now;
        FrmTips ctl_frm_message;
        PIMProcess m_processObj;
        ClsDataUser m_userObj;
        InstrumentGroup m_groupType;
        JcPIMInstrumentInfo[] m_lstInstrument;
        string m_sRCUComName;
        string m_sKnkComName;
        bool m_isProcessStart;
        bool m_isDBC;
        bool m_isLocalConfg = false;

        float m_plot_x_start = 0;
        float m_plot_y_start = 0;

        private void FrmMain_Load(object sender, EventArgs e)
        {
            createModule_pim(true);
            createModule_about(true);
            btn_pim_ok.Visible = true;

            tab_module.Enabled = true;
            m_isDBC = false;
            ctl_main_cbPIMStep.SelectedIndex = 0;
            ctl_main_cbRebootStatus.SelectedIndex = 2;
            m_time_now = new System.Threading.Timer(evt_timer_tick, null, 0, 1000);


            toolStripStatusLabel2.Text = string.Format("员工号: {0}/{1}    姓名: {2}/{3}    账号类型: {4}/{5}",
                                                     m_userObj.sUserID, m_userObj.sUserID2, m_userObj.sUser, m_userObj.sUser2, m_userObj.sRemark, m_userObj.sRemark2);

            toolStripStatusLabel3.Text = string.Format("所在暗室: {0}    设备编号: {1}   管理部门: 质量",
                                                        m_userObj.sDarkroomNum, m_userObj.sEquID);

            IniFile.SetFileName(System.Windows.Forms.Application.StartupPath + "\\JcDevices.ini");
            ctl_main_nudSpeed.Value = 0;
            ctl_main_nudSpeed.Enabled = true;
        }

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            initDataBaseNames();
            initDataInstrument();

            if (m_isLocalConfg)
            {
                ctl_main_btnSet.Text = "本地";
            }
            else
            {
                ctl_main_btnSet.Text = "刷新";
                try
                {
                    initDataConfig_for_antenna();
                }
                catch
                {
                    MessageBox.Show("无法连接服务器!");
                    this.Close();
                }
            }

            if (m_groupType == InstrumentGroup.DESKTOP)
            {
                FrmDeviceManage frmDevice = new FrmDeviceManage();
                frmDevice.ShowDialog();
            }
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            IniFile.SetFileName(System.Windows.Forms.Application.StartupPath + "\\JcDevices.ini");
            IniFile.IniWriteValue("Settings", "RCU_Speed", ctl_main_nudSpeed.Value.ToString());

            if (m_isProcessStart) e.Cancel = true;
            base.OnClosing(e);
        }

        #region Event Handler

        void setDgvFirstDisplay(DataGridView dgv, int start)
        {
            if (dgv.Rows[start].Visible)
                dgv.FirstDisplayedScrollingRowIndex = start;
            else
                dgv.FirstDisplayedScrollingRowIndex = start;
        }

        void m_process_evt_log_handle(object sender, EventArgs e)
        {
            string sLog = sender as string;
            if (e == null)
            {
                this.Invoke(new ThreadStart(delegate
                {
                    TextBox text = ctl_pim_tbLog;
                    text.AppendText(sLog + "\r\n");
                }));
            }
            else
            {
                EventLoggingArgs eLogging = e as EventLoggingArgs;
                this.Invoke(new ThreadStart(delegate
                {
                    if (eLogging.isTips)
                    {
                        if (ctl_frm_message == null)
                        {
                            ctl_frm_message = new FrmTips(sLog);
                            ctl_frm_message.Show(this);
                        }
                    }
                    else
                    {
                        if (ctl_frm_message != null)
                        {
                            ctl_frm_message.Close();
                            ctl_frm_message = null;
                        }
                    }
                }));
            }
        }

        void m_process_evt_complete_all_process_handle(object sender, EventArgs e)
        {
            this.Invoke(new ThreadStart(delegate
                {
                    string sFilePath = System.Windows.Forms.Application.StartupPath + "\\LogMessage";
                    if (!Directory.Exists(sFilePath))
                    {
                        Directory.CreateDirectory(sFilePath);
                    }

                    string sFileName = ctl_main_tbProSN.Text + "PIM" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                    sFileName = sFilePath + "\\" + sFileName; FileStream fs = new FileStream(sFileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                    StreamWriter sw = new StreamWriter(fs);
                    sw.WriteLine(ctl_pim_tbLog.Text);
                    sw.Close();
                    fs.Close();

                    setEnable(true);
                    ctl_main_tbProSN.Text = "";
                    m_isProcessStart = false;

                    if (sender != null)
                    {
                        MessageBox.Show(sender as string);
                    }
                    ctl_main_tbProSN.Focus();
                }));
        }

        void m_process_evt_complete_process_handle(object sender, EventArgs e)
        {
            EventProcessArgs eProcess = e as EventProcessArgs;
            float fMax = (float)eProcess.processObj;
            bool bResult = eProcess.processState;
            this.Invoke(new ThreadStart(delegate
            {
                DataTable table = m_pim_dtShow;
                DataGridView dgv = ctl_pim_dgvData;

                table.Rows[eProcess.processNum]["测试最大值"] = fMax;
                m_pim_dtShowDBC.Rows[eProcess.processNum]["测试最大值"] = fMax - 43;

                if (bResult)
                {
                    table.Rows[eProcess.processNum]["判定结果"] = GDefine.ContentFail;
                    m_pim_dtShowDBC.Rows[eProcess.processNum]["判定结果"] = GDefine.ContentFail;
                    dgv.Rows[eProcess.processNum].Cells["判定结果"].Style.BackColor = ColorTranslator.FromHtml(GDefine.ColorHexFail);
                    dgv.Rows[eProcess.processNum].Cells["测试最大值"].Style.BackColor = ColorTranslator.FromHtml(GDefine.ColorHexFail);
                    dgv.Rows[eProcess.processNum].Cells["实时测试值"].Style.BackColor = ColorTranslator.FromHtml(GDefine.ColorHexFail);
                }
                else
                {
                    table.Rows[eProcess.processNum]["判定结果"] = GDefine.ContentPass;
                    m_pim_dtShowDBC.Rows[eProcess.processNum]["判定结果"] = GDefine.ContentFail;
                    dgv.Rows[eProcess.processNum].Cells["判定结果"].Style.BackColor = ColorTranslator.FromHtml(GDefine.ColorHexPass);
                    dgv.Rows[eProcess.processNum].Cells["测试最大值"].Style.BackColor = ColorTranslator.FromHtml(GDefine.ColorHexPass);
                    dgv.Rows[eProcess.processNum].Cells["实时测试值"].Style.BackColor = ColorTranslator.FromHtml(GDefine.ColorHexPass);
                }

                if (ctl_frm_message != null)
                {
                    ctl_frm_message.Close();
                    ctl_frm_message = null;
                }
            }));
        }

        void m_process_evt_set_settings_handle(object sender, EventArgs e)
        {
            JcPIMDataSettings settings = sender as JcPIMDataSettings;
            EventProcessArgs ePorcess = e as EventProcessArgs;
            this.Invoke(new ThreadStart(delegate
            {
                DataGridView dgv = ctl_pim_dgvData;
                if (ePorcess.processNum >= 0 && ePorcess.processNum < dgv.Rows.Count)
                {
                    dgv.Rows[ePorcess.processNum].Selected = true;
                    int n = (dgv.Height - dgv.ColumnHeadersHeight) / dgv.RowTemplate.Height - 1;
                    if (ePorcess.processNum > n)
                    {
                        if (dgv.Rows[ePorcess.processNum - n].Visible)
                            dgv.FirstDisplayedScrollingRowIndex = ePorcess.processNum - n;
                        else
                            dgv.FirstDisplayedScrollingRowIndex = ePorcess.processNum;
                    }
                    else
                    {
                        if (dgv.Rows[0].Visible)
                            dgv.FirstDisplayedScrollingRowIndex = 0;
                        else
                            dgv.FirstDisplayedScrollingRowIndex = ePorcess.processNum;
                    }

                    m_pim_dtShow.Rows[ePorcess.processNum]["测试最大值"] = "";
                    m_pim_dtShow.Rows[ePorcess.processNum]["判定结果"] = "";
                    m_pim_dtShow.Rows[ePorcess.processNum]["实时测试值"] = "";
                }

                CurveChart plot = ctl_pim_ccPlot;
                plot.Clear();
                if (settings.Mode == ImMode.Freq)
                {
                    plot.SetPlotTitle("扫频模式", "MHz", "");
                    if (settings.RXs != settings.RXe)
                        plot.SetPlotX((float)settings.RXs, (float)settings.RXe);
                }
                else
                {
                    plot.SetPlotTitle("点频模式", "", "");
                    plot.SetPlotX(0, settings.Time);
                    m_plot_x_start = 0;
                    m_plot_y_start = settings.Time + 10;
                }
            }));

        }

        void m_process_evt_get_results_handle(object sender, EventArgs e)
        {
            JcPIMDataResults val = sender as JcPIMDataResults;
            EventProcessArgs ePorcess = e as EventProcessArgs;
            int n = val.No;
            float p1 = val.P1;
            float f1 = val.F1;
            float p2 = val.P2;
            float f2 = val.F2;
            float im_f = val.Im_F;
            float im_v = val.Im_V;
            int n1 = val.n1;
            int n2 = val.n2;

            this.Invoke(new ThreadStart(delegate
            {
                CurveChart plot = ctl_pim_ccPlot;
                DataTable table = m_pim_dtShow;
                TextBox text = ctl_pim_tbLog;

                text.AppendText(val.ToString() + "\r\n");
                if (n1 == 0 && n2 == 0)
                {
                    plot.Add(new PointF(n, im_v), 0);
                    if (n >= m_plot_y_start)
                        m_plot_y_start += 10;
                    plot.SetPlotX(m_plot_x_start, m_plot_y_start);
                }
                else if (n <= n1)
                {
                    plot.Add(new PointF(im_f, im_v), 0);
                }
                else
                {
                    plot.Add(new PointF(im_f, im_v), 1);
                }

                ctl_pim_lblPower.Text = "当前功率： P1=" + p1 + " | P2=" + p2;
                table.Rows[ePorcess.processNum]["实时测试值"] = im_v;
                m_pim_dtShowDBC.Rows[ePorcess.processNum]["实时测试值"] = im_v - 43;
            }));
        }

        void evt_timer_tick(object sender)
        {
            this.toolStripStatusLabel4.Text = DateTime.Now.ToShortTimeString();
        }

        private void tab_module_SelectedIndexChanged(object sender, EventArgs e)
        { }

        private void tab_module_Selecting(object sender, TabControlCancelEventArgs e)
        {
            if (tab_module.SelectedTab == tabPage2)
            {
                if (!m_userObj.HavePower(clsPowerManage.POWER_FEAFTURES.PIM_DEBUG))
                {
                    MessageBox.Show("权限不足！");
                    e.Cancel = true;
                }
            }
        }

        #endregion

        #region Control Created

        void createModule_pim(bool visible)
        {
            int space = 5;
            int width = this.tabPage1.Width;
            int height = this.tabPage1.Height;
            int cb_heigth = gb_pim.Height;

            ctl_pim_container1 = new SplitContainer();
            ctl_pim_container1.Anchor = (AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom);
            ctl_pim_container1.Location = new Point(0 + space, cb_heigth + space * 2);
            ctl_pim_container1.Size = new Size(width - space * 2, height - cb_heigth - space * 2);
            ctl_pim_container1.Orientation = Orientation.Horizontal;
            ctl_pim_container1.SplitterDistance = ctl_pim_container1.Height / 3;

            ctl_pim_dgvData = new DataGridView();
            ctl_pim_dgvData.BackgroundColor = SystemColors.Control;
            ctl_pim_dgvData.Dock = DockStyle.Fill;
            ctl_pim_dgvData.RowHeadersVisible = false;
            ctl_pim_dgvData.AllowUserToAddRows = false;
            ctl_pim_dgvData.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            ctl_pim_dgvData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            ctl_pim_dgvData.ReadOnly = true;
            ctl_pim_dgvData.MultiSelect = false;

            ctl_pim_container2 = new SplitContainer();
            ctl_pim_container2.Dock = DockStyle.Fill;
            ctl_pim_container2.Orientation = Orientation.Horizontal;
            ctl_pim_container2.SplitterDistance = ctl_pim_container2.Height * 2 / 3;

            ctl_pim_ccPlot = new CurveChart();
            ctl_pim_ccPlot.Dock = DockStyle.Fill;

            ctl_pim_tbLog = new TextBox();
            ctl_pim_tbLog.Dock = DockStyle.Fill;
            ctl_pim_tbLog.Multiline = true;
            ctl_pim_tbLog.ReadOnly = true;
            ctl_pim_tbLog.ScrollBars = ScrollBars.Vertical;

            this.tabPage1.Text = "测试";
            this.tabPage1.Controls.Add(ctl_pim_container1);
            ctl_pim_container1.Panel1.Controls.Add(ctl_pim_dgvData);
            ctl_pim_container1.Panel2.Controls.Add(ctl_pim_container2);
            ctl_pim_container2.Panel1.Controls.Add(ctl_pim_ccPlot);
            ctl_pim_container2.Panel2.Controls.Add(ctl_pim_tbLog);
            if (!visible)
                this.tabPage1.Parent = null;
            else
                this.tabPage1.Parent = this.tab_module;
        }

        void createModule_about(bool visible)
        {
            this.tabPage2.Text = "DEBUG";
            if (!visible)
                this.tabPage2.Parent = null;
            else
                this.tabPage2.Parent = this.tab_module;
        }

        #endregion

        #region Data Init

        void initDataInstrument()
        {
            m_lstInstrument = null;
            JcPIMDevicesBuilder.LoadDefaultBand(Application.StartupPath + "\\JcBandInfo.ini");
            IniFile.SetFileName(Application.StartupPath + "\\JcDevices.ini");
            m_sRCUComName = IniFile.IniReadValue("Settings", "RCU_COM", "");
            m_sKnkComName = IniFile.IniReadValue("Settings", "Knock_COM", "");

            try
            {
                if (IniFile.IniReadValue("Settings", "type", "0") == "0")
                {
                    m_groupType = InstrumentGroup.DESKTOP;
                    m_lstInstrument = JcPIMDevicesBuilder.LoadDesktopInstrument(Application.StartupPath);
                }
                else
                {
                    m_groupType = InstrumentGroup.MULTI_BAND;
                    m_lstInstrument = JcPIMDevicesBuilder.LoadMultiBandInstrument(Application.StartupPath);
                }
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); return; }

            m_processObj = new PIMProcessForAntenna(this, m_lstInstrument, m_groupType, m_sRCUComName, m_sKnkComName);
            m_processObj.evt_set_settings_handle += m_process_evt_set_settings_handle;
            m_processObj.evt_get_results_handle += m_process_evt_get_results_handle;
            m_processObj.evt_complete_process_handle += m_process_evt_complete_process_handle;
            m_processObj.evt_complete_all_process_handle += m_process_evt_complete_all_process_handle;
            m_processObj.evt_log_handle += m_process_evt_log_handle;
        }

        void initDataBaseNames()
        {
            if (m_pim_cfgDataBuilder_local == null)
            {
                m_pim_cfgDataBuilder_local = new ClsDataConfigLocalBuilder(GDefine.DBNamePIM);
            }
        }

        bool initDataConfig_for_antenna()
        {
            ctl_main_cbProCode.Items.Clear();
            if (m_pim_lstCfgData_local != null)
                m_pim_lstCfgData_local.Clear();
            if (m_pim_dtShow != null)
                m_pim_dtShow.Clear();

            if (m_isLocalConfg)
            {
                OpenFileDialog frmFile = new OpenFileDialog();
                frmFile.Multiselect = false;
                frmFile.InitialDirectory = Application.StartupPath + "\\config";
                frmFile.Filter = GDefine.FILTER_STRING_PIM;
                if (frmFile.ShowDialog() == DialogResult.OK)
                {
                    ctl_main_cbProCode.Items.Add(frmFile.FileName);
                    ctl_main_cbProCode.SelectedIndex = 0;
                }
            }
            else
            {
                var list = m_pim_cfgDataBuilder_local.getProcodeList();
                if (list != null)
                    ctl_main_cbProCode.Items.AddRange(list);
            }

            return false;
        }

        private void ctl_main_cbProCode_SelectedIndexChanged(object sender, EventArgs e)
        {
            string sProCode = ctl_main_cbProCode.Text;

            if (!m_isLocalConfg)
            {
                m_pim_cfgDataBuilder_local.constructByProcode(sProCode);
                if (m_pim_cfgDataBuilder_local.construct(sProCode, "1.0"))
                {
                    m_pim_lstCfgData_local = m_pim_cfgDataBuilder_local.download(out m_pim_dtShow);
                }
                else
                {
                    MessageBox.Show("未发现配置：" + sProCode);
                    return;
                }
            }
            else
            {
                m_pim_lstCfgData_local = m_pim_cfgDataBuilder_local.download(sProCode, out m_pim_dtShow);
            }

            if (m_pim_lstCfgData_local == null)
            {
                MessageBox.Show("配置错误：" + sProCode);
                return;
            }
            ctl_main_cbRebootStatus.SelectedIndex = m_pim_lstCfgData_local[0].RetSpeed;
            m_enableConfig = new List<bool>();
            m_pim_dtShowDBC = m_pim_dtShow.Copy();
            for (int i = 0; i < m_pim_dtShowDBC.Rows.Count; i++)
            {
                m_enableConfig.Add(true);
                float spec = Convert.ToSingle(m_pim_dtShowDBC.Rows[i]["测试要求"]);
                m_pim_dtShowDBC.Rows[i]["测试要求"] = spec - 43;
            }
            ctl_pim_dgvData.DataSource = m_pim_dtShow.DefaultView;
            ctl_pim_dgvData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            for (int i = 0; i < ctl_pim_dgvData.Columns.Count; i++)
            {
                ctl_pim_dgvData.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
            }

            tab_module.Enabled = true;
            ctl_pim_cbVerConfig.Enabled = false;
        }

        #endregion

        #region Menu control Event

        private void ctl_main_btnSet_Click(object sender, EventArgs e)
        {
            initDataConfig_for_antenna();
        }

        private void ctl_main_tbProSN_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                btn_pim_ok_Click(sender, e);
            }
        }

        #endregion

        #region PIM control Event

        private void ctl_pim_cbVerConfig_SelectedIndexChanged(object sender, EventArgs e)
        {
            downloadPIMModuleData();
        }

        void downloadPIMModuleData()
        {
        }

        #endregion

        #region Running PIM Test

        private void initShowTable()
        {
            ctl_pim_dgvData.DataSource = null;

            for (int i = 0; i < m_pim_dtShow.Rows.Count; i++)
            {
                m_pim_dtShow.Rows[i]["测试最大值"] = "";
                m_pim_dtShow.Rows[i]["判定结果"] = "";
                m_pim_dtShow.Rows[i]["实时测试值"] = "";
                m_pim_dtShowDBC.Rows[i]["测试最大值"] = "";
                m_pim_dtShowDBC.Rows[i]["判定结果"] = "";
                m_pim_dtShowDBC.Rows[i]["实时测试值"] = "";
            }

            if (checkDBC.Checked)
                ctl_pim_dgvData.DataSource = m_pim_dtShowDBC.DefaultView;
            else
                ctl_pim_dgvData.DataSource = m_pim_dtShow.DefaultView;

            ctl_pim_dgvData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            for (int i = 0; i < ctl_pim_dgvData.Columns.Count; i++)
            {
                ctl_pim_dgvData.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
            }
        }

        private void setEnable(bool enable)
        {
            groupBox1.Enabled = enable;
            groupBox11.Enabled = enable;
            btn_pim_ok.Enabled = enable;
            checkDBC.Enabled = enable;

            if (!enable)
                ctl_main_rcuInfo.BackColor = ColorTranslator.FromHtml(GDefine.ColorHexPass);
            else
                ctl_main_rcuInfo.BackColor = Color.Transparent;
        }

        private void btn_pim_ok_Click(object sender, EventArgs e)
        {
            if (tab_module.Enabled == false)
            {
                MessageBox.Show("请设置配置文件!");
                ctl_main_tbProSN.Focus();
                return;
            }

            if (ctl_main_tbProSN.Text.Trim() == "")
            {
                MessageBox.Show("请输入产品SN!");
                ctl_main_tbProSN.Focus();
                return;
            }

            ClsDataProduct productObj = new ClsDataProduct();
            productObj.sProductSN = ctl_main_tbProSN.Text;

            #region 匹配产品代码

            if (!m_isLocalConfg)
            {
                if (!m_processObj.PIMProcessMatchProcode(productObj))
                {
                    ctl_main_tbProSN.Focus();
                    return;
                }



                if (ctl_main_cbProCode.Text == productObj.sProcode)
                {
                    ctl_main_cbProCode_SelectedIndexChanged(null, null);
                }
                else
                {
                    if (ctl_main_cbProCode.Items.IndexOf(productObj.sProcode) < 0)
                    {
                        initDataConfig_for_antenna();
                    }
                    ctl_main_cbProCode.Text = productObj.sProcode;
                }
            }
            else
            {
                productObj.sProcode = ctl_main_cbProCode.Text.Substring(ctl_main_cbProCode.Text.LastIndexOf('\\') + 1);
                ctl_main_cbProCode_SelectedIndexChanged(null, null);
                productObj.enableConfig = m_enableConfig;
            }

            if (m_pim_dtShow == null || m_pim_dtShow.Rows.Count == 0)
            {
                MessageBox.Show("产品代码的配置为空或不存在!");
                ctl_main_tbProSN.Focus();
                return;
            }

            if (productObj.enableConfig.Count == 0)
            {
                for (int i = 0; i < m_pim_lstCfgData_local.Count; i++)
                    productObj.enableConfig.Add(true);
            }
            else
            {
                if (m_pim_lstCfgData_local.Count != productObj.enableConfig.Count)
                {
                    MessageBox.Show("产品代码的可选配置错误！");
                    ctl_main_tbProSN.Focus();
                    return;
                }

                ctl_pim_dgvData.CurrentCell = null;
                for (int i = 0; i < m_pim_lstCfgData_local.Count; i++)
                {
                    ctl_pim_dgvData.Rows[i].Visible = productObj.enableConfig[i];
                    if (productObj.enableConfig[i])
                        ctl_pim_dgvData.CurrentCell = ctl_pim_dgvData.Rows[i].Cells[0];
                }
            }

            #endregion

            productObj.isKnock = ctl_main_checkKnock.Checked;
            productObj.iSpeed = Convert.ToInt32(ctl_main_nudSpeed.Value);

            productObj.sPIMTestStep = ctl_main_cbPIMStep.Text;
            productObj.iRebootStatus = ctl_main_cbRebootStatus.SelectedIndex;
            ctl_pim_tbLog.Text = "";
            m_isProcessStart = true;

            object objConfigList = m_pim_lstCfgData_local;
            setEnable(false);

            if (m_processObj.PIMProcessConfig(objConfigList, productObj, m_userObj))
            {
                m_processObj.PIMProcessStrart();
            }
        }

        #endregion

        #region debug
        RCUrunner m_rcuObj;
        private void button13_Click(object sender, EventArgs e)
        {
            if (m_rcuObj == null)
                m_rcuObj = new RCUrunner(m_sRCUComName);
            bool ret = m_rcuObj.connect("manual test");
            if (ret)
            {
                ctl_dbg_tbLog.AppendText("COM : SUCCESSS\r\n");
                m_rcuObj.reboot();
            }
            else
            {
                ctl_dbg_tbLog.AppendText("COM : Error\r\n");
            }
        }

        private void ctl_dbg_rcuClose_Click(object sender, EventArgs e)
        {
            m_rcuObj.close();
            ctl_dbg_tbLog.AppendText("COM : close\r\n");
        }

        private void ctl_dbg_rcuList_Click(object sender, EventArgs e)
        {
            FrmConfigRCUData rcu_config = new FrmConfigRCUData(null);
            rcu_config.ShowDialog();

            var dicRCUs = m_rcuObj.getRCUInfoList(rcu_config.rsconfig);
            if (dicRCUs != null)
            {
                m_dbg_dicRCUInfo = dicRCUs;
                foreach (var info in dicRCUs)
                {
                    ctl_dbg_tbLog.AppendText(info.Value.SN + "\r\n");
                }

                ctl_dbg_rcuSerial.Items.Clear();
                foreach (var obj in dicRCUs)
                {
                    ctl_dbg_tbLog.AppendText(obj.Key);
                    ctl_dbg_tbLog.AppendText(", ");
                    ctl_dbg_tbLog.AppendText(obj.Value.SN);
                    ctl_dbg_tbLog.AppendText(", ");
                    ctl_dbg_tbLog.AppendText(obj.Value.angle.ToString());
                    ctl_dbg_tbLog.AppendText("\r\n");

                    ctl_dbg_rcuSerial.Items.Add(obj.Key);
                }

                ctl_dbg_rcuSerial.SelectedIndex = 0;
            }

            ctl_dbg_tbLog.AppendText("\r\n");
        }

        Dictionary<string, RCUInfo> m_dbg_dicRCUInfo;

        private void button15_Click(object sender, EventArgs e)
        {
            string sn = m_dbg_dicRCUInfo[ctl_dbg_rcuSerial.Text].SN;
            bool ret = m_rcuObj.set_debug_mode(sn);
            ctl_dbg_tbLog.AppendText(m_rcuObj.cmd + "\r\n");
            if (ret)
                ctl_dbg_tbLog.AppendText(m_rcuObj.result + "\r\n");
            else
                ctl_dbg_tbLog.AppendText("error\r\n");
            ctl_dbg_tbLog.AppendText("\r\n");
        }

        private void button16_Click(object sender, EventArgs e)
        {
            string sn = m_dbg_dicRCUInfo[ctl_dbg_rcuSerial.Text].SN;
            int index = m_dbg_dicRCUInfo[ctl_dbg_rcuSerial.Text].unit.unit;
            int ret = m_rcuObj.get_agl(sn, index);

            ctl_dbg_tbLog.AppendText(m_rcuObj.cmd + "\r\n");
            if (ret != -10000)
            {
                ctl_dbg_tbLog.AppendText(m_rcuObj.result + "\r\n");
                ctl_dbg_tbLog.AppendText("get_agl: " + ret + "\r\n");
            }
            else
                ctl_dbg_tbLog.AppendText("error\r\n");
            ctl_dbg_tbLog.AppendText("\r\n");
        }

        private void ctl_dbg_rcuCali_Click(object sender, EventArgs e)
        {
            string sn = m_dbg_dicRCUInfo[ctl_dbg_rcuSerial.Text].SN;
            int index = m_dbg_dicRCUInfo[ctl_dbg_rcuSerial.Text].unit.unit;
            int ret = m_rcuObj.calibration(sn, index, Convert.ToInt32(ctl_dbg_speed.Value));


            ctl_dbg_tbLog.AppendText(m_rcuObj.cmd + "\r\n");
            if (ret >= 0)
            {
                ctl_dbg_tbLog.AppendText(m_rcuObj.result + "\r\n");
                ctl_dbg_tbLog.AppendText("Cali: " + ret + "\r\n");
            }
            else
                ctl_dbg_tbLog.AppendText("error\r\n");
            ctl_dbg_tbLog.AppendText("\r\n");
        }

        private void button17_Click(object sender, EventArgs e)
        {
            int angle;

            if (!int.TryParse(ctl_dbg_rcuAngle.Text, out angle))
                return;
            string sn = m_dbg_dicRCUInfo[ctl_dbg_rcuSerial.Text].SN;
            int index = m_dbg_dicRCUInfo[ctl_dbg_rcuSerial.Text].unit.unit;
            bool ret = m_rcuObj.set_agl(sn, index, angle, Convert.ToInt32(ctl_dbg_speed.Value));


            ctl_dbg_tbLog.AppendText(m_rcuObj.cmd + "\r\n");
            if (ret)
                ctl_dbg_tbLog.AppendText(m_rcuObj.result + "\r\n");
            else
                ctl_dbg_tbLog.AppendText("error\r\n");
            ctl_dbg_tbLog.AppendText("\r\n");
        }

        private void button19_Click(object sender, EventArgs e)
        {
            m_rcuObj.reboot();
            ctl_dbg_tbLog.AppendText("reboot\r\n");
        }

        private void ctl_dbg_rcuGetinfo_Click(object sender, EventArgs e)
        {
            string sn = m_dbg_dicRCUInfo[ctl_dbg_rcuSerial.Text].SN;
            int index = m_dbg_dicRCUInfo[ctl_dbg_rcuSerial.Text].unit.unit;
            RCUUnit ret = m_rcuObj.get_info(sn, index);

            ctl_dbg_tbLog.AppendText(m_rcuObj.cmd + "\r\n");
            if (ret != null)
            {
                ctl_dbg_tbLog.AppendText(m_rcuObj.result + "\r\n");
            }
            else
                ctl_dbg_tbLog.AppendText("error\r\n");
            ctl_dbg_tbLog.AppendText("\r\n");
        }


        KnockRunner m_knkObj;
        private void button15_Click_1(object sender, EventArgs e)
        {
            if (m_knkObj == null)
                m_knkObj = new KnockRunner(m_sKnkComName);
            bool ret = m_knkObj.connect();
            if (ret)
            {
                ctl_dbg_tbLog.AppendText("COM : SUCCESSS\r\n");
            }
            else
            {
                ctl_dbg_tbLog.AppendText("COM : Error\r\n");
            }
        }

        private void button16_Click_1(object sender, EventArgs e)
        {
            m_knkObj.close();
            ctl_dbg_tbLog.AppendText("COM : close\r\n");
        }

        private void button18_Click(object sender, EventArgs e)
        {
            m_knkObj.start_knock(true);
            ctl_dbg_tbLog.AppendText("konck start\r\n");
        }

        private void button14_Click_1(object sender, EventArgs e)
        {
            m_knkObj.start_knock(false);
            ctl_dbg_tbLog.AppendText("konck stop\r\n");
        }

        private void button13_Click_1(object sender, EventArgs e)
        {
            m_knkObj.set_startNum(Convert.ToInt32(nudKnockNum.Value));
            ctl_dbg_tbLog.AppendText("konck num = " + nudKnockNum.Value.ToString() + "\r\n");
        }

        #endregion

        #region TIPS

        public void RcuTips(string text, bool bShow)
        {
            this.Invoke(new ThreadStart(delegate
            {
                ctl_main_rcuInfo.Text = text;
            }));
        }

        public bool Tips(string text, int btn = 1)
        {
            bool ret = false;
            this.Invoke(new ThreadStart(delegate
            {
                MessageBoxButtons msgBtn = btn == 1 ? MessageBoxButtons.OKCancel : MessageBoxButtons.OK;
                if (MessageBox.Show(text, "提示", msgBtn) == DialogResult.OK)
                {
                    ret = true;
                }
                else
                {
                    ret = false;
                }
            }));
            return ret;
        }

        public int selectTips(string text)
        {
            int ret = 1;
            this.Invoke(new ThreadStart(delegate
            {
                FrmRetry frmTips = new FrmRetry(true);
                DialogResult dr = frmTips.ShowDialog();
                if (dr == DialogResult.No)
                {
                    ret = -1;
                }
                else if (dr == DialogResult.Retry)
                {
                    ret = 1;
                }
                else if (dr == DialogResult.Ignore)
                {
                    ret = 0;
                }
            }));
            return ret;
        }

        #endregion

        private void 重新登陆ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmUser frmlgn = new FrmUser(m_userObj);
            frmlgn.ControlBox = true;
            if (frmlgn.ShowDialog() == DialogResult.OK)
            {
                m_userObj.sDarkroomNum = frmlgn.textBoxDarkroomNum.Text;
                toolStripStatusLabel2.Text = string.Format("员工号: {0}    姓名: {1}    账号类型: {2}",
                                            m_userObj.sUserID, m_userObj.sUser, m_userObj.sRemark);
                toolStripStatusLabel3.Text = string.Format("所在暗室: {0}    设备编号: {1}   管理部门: 质量",
                                                            m_userObj.sDarkroomNum, m_userObj.sEquID);
            }
        }

        private void ConfigToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!m_userObj.HavePower(clsPowerManage.POWER_FEAFTURES.PIM_CONFIG))
            {
                MessageBox.Show("权限不足！");
                return;
            }

            if (m_isLocalConfg)
            {
                FrmConfigNewAntenna frmAnt = new FrmConfigNewAntenna(null);
                frmAnt.ShowDialog();
            }
            else
            {
                FrmConfigAntenna frmAnt = new FrmConfigAntenna(FrmConfigAntenna.TYPE_ANTENNA);
                frmAnt.ShowDialog();
                initDataConfig_for_antenna();
            }
        }

        private void ctl_main_cbRebootStatus_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void 手动上传ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ClsDataUser aUser = new ClsDataUser();
            FrmUser frmlgn = new FrmUser(aUser, 0);
            frmlgn.Text = "需要管理员账号";
            frmlgn.ControlBox = true;
            frmlgn.cbTestItem.Enabled = false;
            frmlgn.textBoxDarkroomNum.Enabled = false;
            frmlgn.textBoxDarkroomNum.Text = m_userObj.sDarkroomNum;
            frmlgn.textBoxUser2.Enabled = false;
            frmlgn.textPassword2.Enabled = false;
            frmlgn.isNeedUser2 = false;
            if (frmlgn.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            if (!aUser.HavePower(clsPowerManage.POWER_FEAFTURES.PIM_MANUAL))
            {
                MessageBox.Show("权限不够!");
                return;
            }


            FrmManualPIM frmManual = new FrmManualPIM(m_userObj);
            frmManual.ShowDialog();
        }

        private void 管理用户ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!m_userObj.HavePower(clsPowerManage.POWER_FEAFTURES.ADMIN))
            {
                MessageBox.Show("权限不足！");
                return;
            }

            FrmUserManage dlgUser = new FrmUserManage(m_userObj.aUser);
            dlgUser.ShowDialog();
        }

        private void DevicesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (m_groupType == InstrumentGroup.DESKTOP)
            {
                FrmDeviceManage frmDevice = new FrmDeviceManage();
                frmDevice.ShowDialog();
            }
        }

        private void 修改密码ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmChangePwd frmpwd = new FrmChangePwd(m_userObj);
            frmpwd.ShowDialog();
        }

        private void checkDBC_CheckedChanged(object sender, EventArgs e)
        {
            if (checkDBC.Checked)
            {
                ctl_pim_dgvData.DataSource = m_pim_dtShowDBC.DefaultView;
            }
            else
            {
                ctl_pim_dgvData.DataSource = m_pim_dtShow.DefaultView;
            }
            ctl_pim_ccPlot.setUnit(checkDBC.Checked);
        }

        private void 配置筛选ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            ClsDataUser aUser = new ClsDataUser();
            FrmUser frmlgn = new FrmUser(aUser, 0);
            frmlgn.Text = "需要管理员账号";
            frmlgn.ControlBox = true;
            frmlgn.cbTestItem.Enabled = false;
            frmlgn.textBoxDarkroomNum.Enabled = false;
            frmlgn.textBoxDarkroomNum.Text = m_userObj.sDarkroomNum;
            frmlgn.textBoxUser2.Enabled = false;
            frmlgn.textPassword2.Enabled = false;
            frmlgn.isNeedUser2 = false;
            if (frmlgn.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            if (!aUser.HavePower(clsPowerManage.POWER_FEAFTURES.PIM_CONFIG_SELECT))
            {
                MessageBox.Show("权限不够!");
                return;
            }

            FrmConfigSelect frmSelect = new FrmConfigSelect(aUser);
            frmSelect.ShowDialog();
        }

        private void rCU配置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!m_userObj.HavePower(clsPowerManage.POWER_FEAFTURES.PIM_CONFIG))
            {
                MessageBox.Show("权限不足！");
                return;
            }

            FrmConfigAntenna frmAnt = new FrmConfigAntenna(FrmConfigAntenna.TYPE_RCU);
            frmAnt.ShowDialog();

        }

        private void ctl_dbg_rcuRevagl_Click(object sender, EventArgs e)
        {

            string sn = m_dbg_dicRCUInfo[ctl_dbg_rcuSerial.Text].SN;
            int index = m_dbg_dicRCUInfo[ctl_dbg_rcuSerial.Text].unit.unit;
            int sor_agl = m_rcuObj.get_agl(sn, index);
            bool ret = m_rcuObj.revertAngle(m_dbg_dicRCUInfo[ctl_dbg_rcuSerial.Text], sor_agl, 0);

            ctl_dbg_tbLog.AppendText(m_rcuObj.cmd + "\r\n");
            if (ret)
                ctl_dbg_tbLog.AppendText(m_rcuObj.result + "\r\n");
            else
                ctl_dbg_tbLog.AppendText("error\r\n");
            ctl_dbg_tbLog.AppendText("\r\n");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            #region csv生成调试




            #endregion
        }

        private void ctl_main_nudSpeed_ValueChanged(object sender, EventArgs e)
        {

        }


        private void 设备调试ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            rflight.FrmDeviceDebug frm = new rflight.FrmDeviceDebug();
            frm.ShowDialog();
            frm.Dispose();
        }

        private void 校准数据手动上传ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmCalConfirmPimManual frm = new FrmCalConfirmPimManual(m_userObj);
            frm.ShowDialog();
            frm.Dispose();
        }

        private void 校准设备信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ClsDataUser aUser = new ClsDataUser();
            FrmUser frmlgn = new FrmUser(aUser, 0);
            frmlgn.Text = "需要管理员账号";
            frmlgn.ControlBox = true;
            frmlgn.cbTestItem.Enabled = false;
            frmlgn.textBoxDarkroomNum.Enabled = false;
            frmlgn.textBoxDarkroomNum.Text = m_userObj.sDarkroomNum;
            //frmlgn.textBoxUser2.Enabled = false;
            //frmlgn.textPassword2.Enabled = false;
            frmlgn.isNeedUser2 = false;
            if (frmlgn.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            if (!aUser.HavePower(clsPowerManage.POWER_FEAFTURES.PIM_CalInstruments))
            {
                MessageBox.Show("权限不够!");
                return;
            }
            aUser.sEquID = m_userObj.sEquID;

            FrmInstrumentsInfo frm = new FrmInstrumentsInfo(aUser);
            frm.ShowDialog();
            frm.Dispose();
        }

        private void 自动校准ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmCalConfirmPim frm = new FrmCalConfirmPim(m_lstInstrument,m_groupType,m_userObj);
            frm.ShowDialog();
            frm.Dispose();
        }
    }
}
